<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->library('session');
	}

	public function index() {
		$data = array('error' => '');
		if (isset($_SESSION[MY_Controller::__ID])) { 
			if($_SESSION[MY_Controller::__ID] == Backend_Controller::__ID_PARAM) {
				redirect(site_url('backend/main/index'));
			} else {
				$this->session->sess_regenerate();
				foreach ($_SESSION as $key => $v) {
					unset($_SESSION[$key]);
				}
				session_write_close();
			}
		}
		if (!empty($_POST)) {
			$this->load->library('form_validation');
			//原来有验证码的
// 			$this->form_validation->validateData(array('username', 'password', 'token'), array(
// 				array('token', 'required|captcha'),
// 				array('username', 'required|min_length[5]'),
// 				array('password', 'required|min_length[6]|validate_password[manager.username]'),
// 			));
			
			//去掉了验证码
			$this->form_validation->validateData(array('username', 'password'), array(
					array('username', 'required|min_length[5]'),
					array('password', 'required|min_length[6]|validate_password[manager.username]'),
			));
				
			if ($this->form_validation->hasErrors()) {
				$data['error'] = $this->form_validation->error;
				return $this->load->view('backend/login/index', $data);
			}
			$dataUpdate = array(
				'last_login_time' => time(),
				'last_login_ip' => $this->input->ip_address(),
			);
			$this->load->model('backend/Admin_model', 'admins');
			$result = $this->admins->update($dataUpdate, array('id' => $this->form_validation->user->id));
			if ($result) {
				$SESS = array(
					'id' => $this->form_validation->user->id,
					'username' => $this->form_validation->username,
					'role' => $this->form_validation->user->role,
					'updated_at' => $dataUpdate['last_login_time'],
					'last_login_ip' => $dataUpdate['last_login_ip'],
					MY_Controller::__ID => Backend_Controller::__ID_PARAM,
				);
				$this->session->set_userdata($SESS);
				session_write_close();
				redirect(site_url('backend/main/index'));
			}
			$data['error'] = 'Syntax error';
		}

		$this->load->view('backend/login/index', $data);
	}	
}
